/*
 * Copyright (c) 2015 Minshenglife. All rights reserved. Minshenglife
 * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 */
package com.sentry.web;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;

import com.sentry.jobs.HttpJob;
import com.sentry.utils.RestReturnData;
import com.sentry.web.bean.HttpJobBean;

import org.joda.time.DateTime;
import org.joda.time.LocalDateTime;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author WuBo (wub1@minshenglife.com)
 *
 */
@RestController
@RequestMapping("/job")
public class HTTPJobController extends RestControllerSupport {

    @Autowired
    private Scheduler sched;



    @RequestMapping(value = "/http", method = RequestMethod.GET)
    public RestReturnData<List<HttpJobBean>> list(String group)
            throws SchedulerException {
        RestReturnData<List<HttpJobBean>> r = new RestReturnData<>();
        List<HttpJobBean> jobs = new ArrayList<>(0);
        Set<JobKey> jks = sched.getJobKeys(GroupMatcher.jobGroupEquals(group));
        jks.forEach(jk -> {
            try {
                jobs.add(new HttpJobBean(
                        sched.getJobDetail(jk).getKey().toString()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        r.setData(jobs);
        return r;
    }

    @RequestMapping(value="/http",method=RequestMethod.POST)
    public RestReturnData<String> add(@RequestBody HttpJobBean httpJob)
            throws SchedulerException {
        Trigger trigger =
                newTrigger().withIdentity(httpJob.getName(), httpJob.getGroup())
                        .startAt(DateTime.now().plusMinutes(1).toDate())
                        .withSchedule(simpleSchedule()
                                .repeatForever()
                                .withIntervalInSeconds(httpJob.getInterval()))
                        .build();

        JobDetail job = newJob(HttpJob.class)
                .withIdentity(httpJob.getName(), httpJob.getGroup())
                .usingJobData("url", httpJob.getUrl()).storeDurably().build();
        Date d = sched.scheduleJob(job, trigger);
        sched.pauseJob(JobKey.jobKey(httpJob.getName(), httpJob.getGroup()));

        RestReturnData<String> r = new RestReturnData<>();
        r.setData(LocalDateTime.fromDateFields(d)
                .toString("yyyy-MM-dd HH:mm:ss"));
        return r;
    }

    @RequestMapping("/http/start")
    public RestReturnData<String> start(@RequestBody HttpJobBean httpJob)
            throws SchedulerException {
        RestReturnData<String> r = new RestReturnData<>();
        JobDetail job = sched.getJobDetail(
                JobKey.jobKey(httpJob.getName(), httpJob.getGroup()));
        sched.resumeJob(job.getKey());
        r.setData("true");
        return r;
    }
    
    @RequestMapping("/http/stop")
    public RestReturnData<String> stop(@RequestBody HttpJobBean httpJob)
            throws SchedulerException {
        RestReturnData<String> r = new RestReturnData<>();
        JobDetail job = sched.getJobDetail(
                JobKey.jobKey(httpJob.getName(), httpJob.getGroup()));
        sched.pauseJob(job.getKey());
        r.setData("true");
        return r;
    }    

}
